package 网络编程.udp;

import 网络编程.Log;

import java.io.UnsupportedEncodingException;
import java.net.*;
import java.util.HashMap;
import java.util.Scanner;

public class ClientVersion1 {
    public static final int port = 8888;
    private static HashMap<String, String> map = new HashMap<>();
    static {
        map.put("apple","苹果");
        map.put("book","书");
        map.put("bicycle","自行车");
        Log.println("字典初始化完成");
    }
    public static void main(String[] args) throws Exception {
        //1,创建DatagramSocket
        Log.println("开始创建UDP Socket");
        DatagramSocket socket = new DatagramSocket(port);
        Log.println("UDP Socket创建完成");
        Scanner sc = new Scanner(System.in);
        System.out.print("输入要翻译的单词：");

       while (sc.hasNextLine()){
           //2,创建请求数据包
           String request = sc.nextLine();
           Log.println("请求的数据为" + request);
           byte[] buf = request.getBytes("UTF-8");
           Log.println("准备创建请求数据包");
           DatagramPacket requestPacket = new DatagramPacket(buf,0,buf.length, InetAddress.getLoopbackAddress(),TranslateServer.port);
            Log.println("请求数据包创建完成");

           //3,发送请求
           Log.println("发送请求");
           socket.send(requestPacket);
           Log.println("请求发送成功");

           //4,接收响应
           byte[] bytes = new byte[1024];
           DatagramPacket responsePacket = new DatagramPacket(bytes,bytes.length);
           Log.println("开始接收响应");
           socket.receive(responsePacket);
           byte[] data = responsePacket.getData();
           String res = new String(data,0,responsePacket.getLength(),"UTF-8");
           Log.println("请求结果为：" + res);
           Log.println("对方的IP为" + requestPacket.getAddress());
           Log.println("对方的端口为" + requestPacket.getPort());
           System.out.print("输入要翻译的单词：");
       }

        //5,关闭资源
        socket.close();
       Log.println("关闭Socket");
    }
}
